local file = io.open(arg[1],"rb");
assert(file);

local data = file:read('*a');
local rom_size = #data;
local align = rom_size % 1024;
rom_size = rom_size + align;
local out_file = arg[2] or 'out.bin';
local out = io.open(out_file,"wb");
local lb = function(a)
    return data:byte(a+1) or 0xff;
end

local lh = function(a) return lb(a) + lb(a+1)*0x100; end
local lw = function(a) return lh(a) + lh(a+2)*0x10000; end

local addr = 0x80000000;
while(addr<0x80000400)do
    --BLOB被省略.需要忽略
    addr = addr + 4;
end

local f = string.format;
local data_size = 0;
local write_data = function(rom_addr)
    local buff_addr = 0x80000 + 0x1000;     --
    local buff_size = 8*1024;
    while(buff_size>0)do
        -- if(buff_size%1024==0)then
        --     print(f('puts %dKBytes',data_size));
        --     data_size = data_size + 1;
        -- end
        -- print(f('mww 0x%08x 0x%08x',buff_addr,lw(rom_addr)));
        out:write(string.char(lb(rom_addr))..
        string.char(lb(rom_addr+1))..
        string.char(lb(rom_addr+2))..
        string.char(lb(rom_addr+3)));
        data_size = data_size + 4;


        buff_size = buff_size - 4;
        buff_addr = buff_addr + 4;
        rom_addr = rom_addr + 4;
        if(rom_addr>rom_size)then break; end
    end

    return rom_addr,8*1024-buff_size;
end

local rom_addr = 0;
local w_size = 0;
while(rom_addr<rom_size)do
    rom_addr,w_size = write_data(rom_addr);
    --print('puts "write buf"');
    print(f("load_image_bin %s 0x%08x 0x%08x %d",out_file,data_size - w_size,0x81000, w_size));
    print(f('puts "program %.2fKBytes"',data_size/1024));
    print(f('xpi_nor_call $xpi_nor_program $HPM_XPI0 4 $::xpi_nor_config 0x%08x 0x%08x %d',0x81000,addr-0x80000000,8*1024));
    --print('puts [xpi_nor_exec]');
    print('xpi_nor_exec');
    print('xpi_nor_exec_wait');
    addr = addr + w_size;
end

out:close();
